<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Controller;
use think\Db;
use redis\RedisPackage;
require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');

/**
 * 公共方法类
 */
class Common extends Controller
{
    /**
     * 获取项目基础配置项
     * User:@hang
     */
    public function getConfigValue($config_key)
    {
        $IndexTableModel = New IndexTableModel();
        $configValue = $IndexTableModel->getFind('fa_config',"`config_key` = '$config_key'",'config_value');
        return isset($configValue['config_value'])?$configValue['config_value']:'';
    }

    /**
     * 获取多个项目基础配置项
     * User:@hang
     */
    public function getConfigValueMore($config_key_more)
    {
        $IndexTableModel = New IndexTableModel();
        $configValue = $IndexTableModel->getList('fa_config',"`config_key` in($config_key_more)",'config_key,config_value','id asc');
        $arr = array();
        if(!empty($configValue)){
            foreach ($configValue as $k=>$v){
                $arr[$v['config_key']] = $v['config_value'];
            }
        }
        return $arr;
    }

    /**
     * 获取项目三方配置项
     * User:@hang
     */
    public function getTripartiteConfigValue($config_key)
    {
        $IndexTableModel = New IndexTableModel();
        $configValue = $IndexTableModel->getFind('fa_config_tripartite',"`config_key` = '$config_key'",'config_value');
        return isset($configValue['config_value'])?$configValue['config_value']:'';
    }


    /**
     * 增加或减少用户 可提现油票数
     * member_id   用户id
     * type 1增加   2减少
     * num  增加或减少的油票数量
     */
    public function incStampMoney($member_id,$type,$num)
    {
        if($num == 0){return 200;}
        $IndexTableModel = New IndexTableModel();
        //查询用户 可提现油票数
        $memberFundInfo = $IndexTableModel->getFind('fa_member_fund',array('member_id'=>$member_id),'stamp_money');
        if($type == 1){
            //增加
            $overNum = delete0(bcadd($memberFundInfo['stamp_money'],$num,2));
        }else{
            if($num > $memberFundInfo['stamp_money']){
                return 500;
            }
            //减少
            $overNum = delete0(bcsub($memberFundInfo['stamp_money'],$num,2));
        }
        //修改用户 可提现油票数
        $res = $IndexTableModel->editInfo('fa_member_fund',array('member_id'=>$member_id),array('stamp_money'=>$overNum));
        if($res){
            return 200;
        }else{
            return 500;
        }
    }

    /**
     * 增加或减少用户 不可提现油票数
     * member_id   用户id
     * type 1增加   2减少
     * num  增加或减少的油票数量
     */
    public function incNoStampMoney($member_id,$type,$num)
    {
        if($num == 0){return 200;}
        $IndexTableModel = New IndexTableModel();
        //查询用户 不可提现油票数
        $memberFundInfo = $IndexTableModel->getFind('fa_member_fund',array('member_id'=>$member_id),'no_stamp_money');
        if($type == 1){
            //增加
            $overNum = delete0(bcadd($memberFundInfo['no_stamp_money'],$num,2));
        }else{
            if($num > $memberFundInfo['no_stamp_money']){
                return 500;
            }
            //减少
            $overNum = delete0(bcsub($memberFundInfo['no_stamp_money'],$num,2));
        }
        //修改用户 不可提现油票数
        $res = $IndexTableModel->editInfo('fa_member_fund',array('member_id'=>$member_id),array('no_stamp_money'=>$overNum));
        if($res){
            return 200;
        }else{
            return 500;
        }
    }


    /**
     * 增加或减少用户 曝光次数
     * member_id   用户id
     * type 1增加   2减少
     * num  增加或减少的曝光次数
     */
    public function incExposureNum($member_id,$type,$num)
    {
        if($num == 0){return 200;}
        $IndexTableModel = New IndexTableModel();
        //查询用户 曝光次数
        $memberFundInfo = $IndexTableModel->getFind('fa_member_fund',array('member_id'=>$member_id),'exposure_num');
        if($type == 1){
            //增加
            $overNum = delete0(bcadd($memberFundInfo['exposure_num'],$num,2));
        }else{
            if($num > $memberFundInfo['exposure_num']){
                return 500;
            }
            //减少
            $overNum = delete0(bcsub($memberFundInfo['exposure_num'],$num,2));
        }
        //修改用户 曝光次数
        $res = $IndexTableModel->editInfo('fa_member_fund',array('member_id'=>$member_id),array('exposure_num'=>$overNum));
        if($res){
            return 200;
        }else{
            return 500;
        }
    }


    /**
     * 查询某用户油票是否充足
     * User:@hang
     * $member_id 用户ID
     * $stamp_num 要消费的油票数
     * 返回数据  is_enough：油票是否充足 1充足 2不足      x_stamp_money：需要消耗的可提现油票数      x_nostamp_money：需要消耗的不可提现油票数
     */
    public function checkStampAdequacy($member_id,$stamp_num)
    {
        $data = array();
        $data['is_enough'] = '2';//油票是否充足 1充足 2不足
        $data['x_stamp_money'] = '0';//需要消耗的可提现油票数
        $data['x_nostamp_money'] = '0';//需要消耗的不可提现油票数
        if(empty($stamp_num)){
            $data['is_enough'] = '1';
            return ['code'=>'200','msg'=>'查询成功','data'=>$data];
        }
        $IndexTableModel = New IndexTableModel();
        //查询用户 可提现/不可提现 油票数
        $memberFundInfo = $IndexTableModel->getFind('fa_member_fund',array('member_id'=>$member_id),'id,member_id,stamp_money,no_stamp_money');
        if(empty($memberFundInfo)) return ['code'=>'500','msg'=>'用户钱包信息查询失败','data'=>[]];
        if($memberFundInfo['no_stamp_money'] == 0){
            //不可提现油票为0 判断可提现油票是否够
            if($memberFundInfo['stamp_money'] < $stamp_num){
                //余额不足
                return ['code'=>'200','msg'=>'查询成功','data'=>$data];
            }
            $data['is_enough'] = '1';//充足
            $data['x_stamp_money'] = $stamp_num;//消耗的全是可提现油票
        }else{
            if($memberFundInfo['no_stamp_money'] < $stamp_num){
                //消耗油票大于不可提现油票数
                $cha = bcsub($stamp_num,$memberFundInfo['no_stamp_money'],2);
                if($cha > $memberFundInfo['stamp_money']){
                    //差额还大于可提现油票 余额不足
                    return ['code'=>'200','msg'=>'查询成功','data'=>$data];
                }
                //即消耗不可提现油票 又要消耗可提现油票
                $data['is_enough'] = '1';//充足
                $data['x_stamp_money'] = delete0($cha);//需要消耗的可提现油票数
                $data['x_nostamp_money'] = $memberFundInfo['no_stamp_money'];//需要消耗的不可提现油票数
            }else{
                //消耗油票小于不可提现油票数
                $data['is_enough'] = '1';//充足
                $data['x_nostamp_money'] = $stamp_num;//消耗的全是不可提现油票
            }
        }
        return ['code'=>'200','msg'=>'查询成功','data'=>$data];
    }


    /**
     * 插入财务日志
     * User:@hang
     * 具体每个入参查看 数据库 fa_finance 字段备注
     */
    public function setFinance($member_id,$d_member_id,$g_table,$g_id,$type,$money_type,$status,$money,$content,$chat_type){
        $IndexTableModel = New IndexTableModel();
        $memberFundInfo = $IndexTableModel->getFind('fa_member_fund',array('member_id'=>$member_id),'id,member_id,stamp_money,no_stamp_money,exposure_num');
        if(empty($memberFundInfo)) return ['code'=>'500','msg'=>'用户钱包信息查询失败','data'=>[]];
        $member_money = '0';
        if($money_type == 1){$member_money = $memberFundInfo['no_stamp_money'];}//插入当时剩余不可提现油票数
        if($money_type == 2){$member_money = $memberFundInfo['stamp_money'];}//插入当时剩余可提现油票数
        if($money_type == 3){$member_money = $memberFundInfo['exposure_num'];}//插入当时剩余曝光量
        $data = array();
        $data['member_id'] = $member_id;
        $data['d_member_id'] = $d_member_id;
        $data['g_table'] = $g_table;
        $data['g_id'] = $g_id;
        $data['type'] = $type;
        $data['money_type'] = $money_type;
        $data['status'] = $status;
        $data['money'] = $money;
        $data['member_money'] = $member_money;
        $data['content'] = $content;
        $data['add_time'] = time();
        $data['date_time'] = date('Y-m-d H:i:s',$data['add_time']);
        $data['chat_type'] = $chat_type;
        $res = $IndexTableModel->addInfo('fa_finance',$data);
        if(empty($res)){
            return ['code'=>'500','msg'=>'财务日志写入失败','data'=>[]];
        }
        return ['code'=>'200','msg'=>'财务日志写入成功','data'=>['id'=>$res]];
    }


    /**
     * 天地图 根据经纬度解析省市区
     * User:@hang
     * $lon 经度  $lat 纬度
     */
    public function lonLatGetAddress($lon,$lat)
    {
        $address = '未知地址';$province = '未知省';$city = '未知市';$area = '未知区';$province_code = '0';$city_code = '0';$area_code = '0';
        $tdtsecretkey = $this->getTripartiteConfigValue('tdtsecretkey');
        $url = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':".$lon.",'lat':".$lat.",'ver':1}&type=geocode&tk=$tdtsecretkey";
        $arrjson = getcurl($url);
        $memberJwAddressData = json_decode($arrjson,true);
        if(!empty($memberJwAddressData)){
            if(is_array($memberJwAddressData)){
                if(isset($memberJwAddressData['status'])){
                    if($memberJwAddressData['status'] == 0){
                        if(isset($memberJwAddressData['result']['formatted_address'])){
                            if(!empty($memberJwAddressData['result']['formatted_address'])){
                                $address = $memberJwAddressData['result']['formatted_address'];//详细地址
                            }
                        }
                        if(isset($memberJwAddressData['result']['addressComponent']['province']) && isset($memberJwAddressData['result']['addressComponent']['province_code'])){
                            if(!empty($memberJwAddressData['result']['addressComponent']['province']) && !empty($memberJwAddressData['result']['addressComponent']['province_code'])){
                                $province = $memberJwAddressData['result']['addressComponent']['province'];//省
                                $province_code = substr($memberJwAddressData['result']['addressComponent']['province_code'], -6);//省code
                            }
                        }
                        if(isset($memberJwAddressData['result']['addressComponent']['city']) && isset($memberJwAddressData['result']['addressComponent']['city_code'])){
                            if(!empty($memberJwAddressData['result']['addressComponent']['city_code'])){
                                $city = $memberJwAddressData['result']['addressComponent']['city'];//市
                                $city_code = substr($memberJwAddressData['result']['addressComponent']['city_code'], -6);//市code
                            }
                        }
                        if(isset($memberJwAddressData['result']['addressComponent']['county']) && isset($memberJwAddressData['result']['addressComponent']['county_code'])){
                            if(!empty($memberJwAddressData['result']['addressComponent']['county']) && !empty($memberJwAddressData['result']['addressComponent']['county_code'])){
                                $area = $memberJwAddressData['result']['addressComponent']['county'];//区
                                $area_code = substr($memberJwAddressData['result']['addressComponent']['county_code'], -6);//区code
                            }
                        }
                    }
                }
                if(empty($province_code) || empty($city_code) || empty($area_code)){
                    return ['code'=>'500','msg'=>'经纬度信息错误','data'=>[]];
                }
                return ['code'=>'200','msg'=>'查询成功','data'=>['address'=>$address,'province'=>$province,'city'=>$city,'area'=>$area,'province_code'=>$province_code,'city_code'=>$city_code,'area_code'=>$area_code]];
            }else{
                return ['code'=>'500','msg'=>'天地图返回信息解析错误','data'=>[]];
            }
        }else{
            return ['code'=>'500','msg'=>'天地图根据经纬度解析省市区失败','data'=>[]];
        }
    }


    /**
     * 天地图 根据详细地址获取经纬度
     * User:@hang
     * $address 详细地址
     */
    public function addressGetLonLat($address)
    {
        $lon = '0';//经度
        $lat = '0';//纬度
        $tdtsecretkey = $this->getTripartiteConfigValue('tdtsecretkey');
        $url = 'http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"'.$address.'"}&tk='.$tdtsecretkey;
        $arrjson = getcurl($url);
        $memberJwAddressData = json_decode($arrjson,true);
        if(empty($memberJwAddressData)){
            return ['code'=>'500','msg'=>'天地图返回信息解析错误','data'=>['lon'=>$lon,'lat'=>$lat]];
        }
        if(!is_array($memberJwAddressData)){
            return ['code'=>'500','msg'=>'天地图返回信息格式错误','data'=>['lon'=>$lon,'lat'=>$lat]];
        }
        if(!isset($memberJwAddressData['status'])){
            return ['code'=>'500','msg'=>'天地图状态码不存在','data'=>['lon'=>$lon,'lat'=>$lat]];
        }
        if($memberJwAddressData['status'] != 0){
            return ['code'=>'500','msg'=>'天地图状态码错误','data'=>['lon'=>$lon,'lat'=>$lat]];
        }
        if(!isset($memberJwAddressData['location']['lon'])){
            return ['code'=>'500','msg'=>'天地图返回经度不存在','data'=>['lon'=>$lon,'lat'=>$lat]];
        }
        if(!isset($memberJwAddressData['location']['lat'])){
            return ['code'=>'500','msg'=>'天地图返回纬度不存在','data'=>['lon'=>$lon,'lat'=>$lat]];
        }
        if(empty($memberJwAddressData['location']['lon']) || empty($memberJwAddressData['location']['lat'])){
            return ['code'=>'500','msg'=>'天地图返回经纬度为空','data'=>['lon'=>$lon,'lat'=>$lat]];
        }
        $lon = $memberJwAddressData['location']['lon'];
        $lat = $memberJwAddressData['location']['lat'];
        return ['code'=>'200','msg'=>'根据详细地址获取经纬度成功','data'=>['lon'=>$lon,'lat'=>$lat]];
    }


    /**
     * 用户喜好存入redis
     * User:@hang
     */
    public function redisMemberLabel($member_id){
        $IndexTableModel = New IndexTableModel();
        $list = $IndexTableModel->getList('fa_member_label',"`member_id` = '$member_id'","label_id",'num desc,add_time desc');
        $memberLableStr = '';
        foreach ($list as $k=>$v){
            $memberLableStr .= $v['label_id'].',';
        }
        $memberLableStr = rtrim($memberLableStr,',');
        $redis = New RedisPackage();
        $redis->hSet('MemberLabel','member_id_'.$member_id,$memberLableStr);
        return 200;
    }


    /**
     * 百度云接口 姓名+身份证号 认证
     * User:@hang
     */
    public function getRealNameAuthenticationInfo($name,$idcard)
    {
        return ['code'=>200,'msg'=>'实名认证通过','data'=>[]];
    }


    /**
     * 更新富豪榜信息
     * $member_id 所属用户ID
     * $num  群礼物发送油票数
     * User:@hang
     */
    public function setRankingFh($member_id,$num)
    {
        $IndexTableModel = New IndexTableModel();
        $rankingInfo = $IndexTableModel->getFind('fa_ranking_fh',"`member_id` = '{$member_id}'",'*');
        if(empty($rankingInfo)){
            $IndexTableModel->addInfo('fa_ranking_fh',array('member_id'=>$member_id,'num'=>$num,'add_time'=>time()));
        }else{
            $overNum = delete0(bcadd($rankingInfo['num'],$num,4));
            $IndexTableModel->editInfo('fa_ranking_fh',"`id` = '{$rankingInfo['id']}'",array('num'=>$overNum,'add_time'=>time()));
        }
        return 200;
    }

    /**
     * 更新邀请榜信息
     * $member_id 所属用户ID
     * $num  邀请人数
     * User:@hang
     */
    public function setRankingYq($member_id,$num)
    {
        $IndexTableModel = New IndexTableModel();
        $rankingInfo = $IndexTableModel->getFind('fa_ranking_yq',"`member_id` = '{$member_id}'",'*');
        if(empty($rankingInfo)){
            $IndexTableModel->addInfo('fa_ranking_yq',array('member_id'=>$member_id,'num'=>$num,'add_time'=>time()));
        }else{
            $overNum = bcadd($rankingInfo['num'],$num,0);
            $IndexTableModel->editInfo('fa_ranking_yq',"`id` = '{$rankingInfo['id']}'",array('num'=>$overNum,'add_time'=>time()));
        }
        return 200;
    }

    /**
     * 更新活跃榜信息
     * $member_id 所属用户ID
     * $num  评论数
     * User:@hang
     */
    public function setRankingHy($member_id,$num)
    {
        $IndexTableModel = New IndexTableModel();
        $rankingInfo = $IndexTableModel->getFind('fa_ranking_hy',"`member_id` = '{$member_id}'",'*');
        if(empty($rankingInfo)){
            $IndexTableModel->addInfo('fa_ranking_hy',array('member_id'=>$member_id,'num'=>$num,'add_time'=>time()));
        }else{
            $overNum =bcadd($rankingInfo['num'],$num,0);
            $IndexTableModel->editInfo('fa_ranking_hy',"`id` = '{$rankingInfo['id']}'",array('num'=>$overNum,'add_time'=>time()));
        }
        return 200;
    }


    /**
     * 完成车辆认证，执行邀请奖励（奖励油票，奖励曝光量）
     * $member_id 邀请人ID
     * $b_member_id 被邀请人ID
     * User:@hang
     */
    public function actionInviteRewards($member_id,$b_member_id)
    {
        $IndexTableModel = New IndexTableModel();
        $inviteInfo = $IndexTableModel->getFind('fa_member_invite',"`member_id` = '{$member_id}' and `b_member_id` = '{$b_member_id}'",'*');
        if(empty($inviteInfo)){
            return 200;
        }
        if($inviteInfo['status'] == 2){
            return 200;
        }
        $invitationpoolnum = $this->getConfigValue('invitationpoolnum');//【邀请奖池】油票余额数
        $clrzcgyqzjlbg = $this->getConfigValue('clrzcgyqzjlbg');//被邀请者车辆认证成功，奖励邀请者曝光数
        $clrzcgyqz = $this->getConfigValue('clrzcgyqz');//被邀请者车辆认证成功，奖励邀请者【邀请奖池】邮票数
        $service_content = '';
        if($clrzcgyqz > $invitationpoolnum){
//            return 200;
            $clrzcgyqz = 0;
            $service_content = '您邀请的用户已完成圈层认证，邀请奖池油票不足，未奖励您油票。';
        }
        // 启动事务
        Db::startTrans();
        if($clrzcgyqz != 0){
            //增加邀请者油票数奖励
            $yp_res = $this->incStampMoney($member_id,1,$clrzcgyqz);
            if($yp_res != 200){
                Db::rollback(); // 回滚事务
                return '增加邀请者油票数奖励失败';
            }
            //增加邀请者油票数奖励财务日志
            $finRes = $this->setFinance($member_id,$b_member_id,'fa_member_invite',$inviteInfo['id'],10,2,1,$clrzcgyqz,'邀请奖励油票',0);
            if($finRes['code'] != 200){
                Db::rollback(); // 回滚事务
                return '增加邀请者油票数奖励财务日志失败';
            }
            //降低 【邀请奖池】油票余额数
            $invitationpoolnumOver = delete0(bcsub($invitationpoolnum,$clrzcgyqz,2));
            $IndexTableModel->editInfo('fa_config',"`config_key` = 'invitationpoolnum'",array('config_value'=>$invitationpoolnumOver));
        }
        if($clrzcgyqzjlbg != 0){
            //增加邀请者曝光量奖励
            $yp_res = $this->incExposureNum($member_id,1,$clrzcgyqzjlbg);
            if($yp_res != 200){
                Db::rollback(); // 回滚事务
                return '增加邀请者曝光量奖励失败';
            }
            //增加邀请者曝光量奖励财务日志
            $finRes = $this->setFinance($member_id,$b_member_id,'fa_member_invite',$inviteInfo['id'],24,3,1,$clrzcgyqzjlbg,'邀请奖励曝光量',0);
            if($finRes['code'] != 200){
                Db::rollback(); // 回滚事务
                return '增加邀请者曝光量奖励财务日志失败';
            }
        }
        //修改邀请日志
        $res = $IndexTableModel->editInfo('fa_member_invite',"`id` = '{$inviteInfo['id']}'",array('status'=>2,'y_stamp'=>$clrzcgyqz,'y_exposure'=>$clrzcgyqzjlbg,'jl_time'=>time()));
        if(empty($res)){
            Db::rollback(); // 回滚事务
            return '修改邀请日志失败';
        }
        //增加服务通知
        $content = empty($service_content)?'您邀请的用户已完成圈层认证，您已获得邀请奖励。':$service_content;
        $newRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>11,'member_id'=>$b_member_id,'j_member_id'=>$member_id,'g_table'=>'fa_member_invite','g_id'=>$inviteInfo['id'],'content'=>$content,'is_read'=>0,'add_time'=>time()));
        if(empty($newRes)){
            Db::rollback(); // 回滚事务
            return '增加服务通知失败';
        }
        Db::commit();
        return 200;
    }


    /**
     * 获取后台管理端  用户的前端账号ID  和  是否可以看见真实在线人数
     * User:@hang
     */
    public function getMyAccountNumber($admin_id){
        $arr = array();
        $arr['show_member'] = -1;//0看全部  -1谁也不能看  否则看自己
        $arr['show_zx'] = -1;//0可以看 -1谁也不能看
        $IndexTableModel = New IndexTableModel();
        $adminInfo = $IndexTableModel->getFind('admin_user',"`id` = '{$admin_id}'",'id,username,is_qt,is_zx_qt');
        if(!empty($adminInfo)){
            $membmerInfo = $IndexTableModel->getFind('fa_member',"`me_phone` = '{$adminInfo['username']}'",'member_id');
            if(!empty($membmerInfo)){
                $arr['show_member'] = $membmerInfo['member_id'];//0看全部  -1谁也不能看  否则看自己
            }
            if($adminInfo['is_qt'] == 1){
                $arr['show_member'] = 0;//0看全部  -1谁也不能看  否则看自己
            }
            if($adminInfo['is_zx_qt'] == 1){
                $arr['show_zx'] = 0;//0看全部  -1谁也不能看  否则看自己
            }
        }
        return $arr;
    }


    /**
     * 获取后台管理端用户的前端 所有下级人员ID
     * User:@hang
     */
    public function getMyXmemberIdStr($admin_id){
        $q_member_id = -1;//0看全部 -1谁也不能看  否则看所有下级人员ID逗号拼接
        $IndexTableModel = New IndexTableModel();
        $adminInfo = $IndexTableModel->getFind('admin_user',"`id` = '{$admin_id}'",'id,username,is_qt');
        if(!empty($adminInfo)){
            if($adminInfo['is_qt'] == 1){
                return 0;
            }
            $membmerInfo = $IndexTableModel->getFind('fa_member',"`me_phone` = '{$adminInfo['username']}'",'member_id');
            if(!empty($membmerInfo)){
                $q_member_id = $membmerInfo['member_id'];
                $member_str = $q_member_id;
                $xjStr = $q_member_id;
                for ($i = 0; $i < 10; ++$i) {
                    $xjStr = $this->getXjLsit($xjStr);
                    if(empty($xjStr)){
                        break;
                    }
                    $member_str = $member_str.','.$xjStr;
                }
                return $member_str;
            }
        }
        return $q_member_id;
    }


    public function getXjLsit($member_str)
    {
        if(empty($member_str)) return 0;
        $res = Db::table("fa_member")->where("`me_parent` in($member_str)")->column('member_id');
        if(empty($res)) return 0;
        $strres = implode(',',$res);
        return $strres;
    }






}